import React, { FC, useRef } from "react";
import { Button } from "antd";
import XLSX from 'xlsx'

const DownLoad: FC<any> = ({
    children,
    excelData,
    onSuccess
}) => {
    const fileRef: any = useRef()
    const fixData = (data: any) => {
        let o = ''
        let l = 0
        const w = 10240
        for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(1 * w, l * w + w)))
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)))
        return o
    }
    const getHeaderRow = (sheet: any) => {
        const headers = []
        const range = XLSX.utils.decode_range(sheet['!ref'])
        let C
        const R = range.s.r
        for (C = range.s.c; C <= range.e.c; ++C) {
            const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
            let hdr = 'UNKNOWN' + C
            if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
            headers.push(hdr)
        }
        return headers
    }
    const generateData = ({ header, results }: any) => {
        excelData.header = header
        excelData.results = results
        onSuccess && onSuccess(excelData)
    }
    const handleClick = (e: any) => {
        const files = e.target.files
        const rawFile = files[0]
        if (!rawFile) return;
        fileRef.current.value = null
        return new Promise((resolve: any, reject: any) => {
            const reader = new FileReader()
            reader.onload = (e: any) => {
                const data = e.target.result
                const fixedData = fixData(data)
                const workbook = XLSX.read(btoa(fixedData), { type: 'base64' })
                const firstSheetName = workbook.SheetNames[0]
                const worksheet = workbook.Sheets[firstSheetName]
                const header = getHeaderRow(worksheet)
                const results = XLSX.utils.sheet_to_json(worksheet)
                generateData({ header, results })
                resolve()
            }
            reader.readAsArrayBuffer(rawFile)
        })
    }
    const handleUpload = () => {
        fileRef.current.click()
    }
    return (
        <div>
            <input ref={fileRef} style={{ display: 'none' }} className="excel-upload-input" type="file" accept=".xlsx, .xls" onChange={handleClick} />
            <div onClick={handleUpload}>
                {
                    children ? children : <Button type="primary">导出数据</Button>
                }
            </div>
        </div>
    )
}

export default DownLoad